using System;   
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using ResourceBlender.Core;

/// <summary>
/// A template for GridView columns which contain a label and a textbox
/// </summary>
public class GridViewTemplate : ITemplate { //LocalPage,
    private ListItemType templateType;
    private string columnName,
                   friendlyName,
                   twoLetterISOCode;
    private bool defaultLanguage;

    /// <summary>
    /// Initializes a new GridViewTemplate for the specified column name
    /// </summary>
    /// <param name="type">The field type.</param>
    /// <param name="colname">The field in the database which will be displayed.</param>
    /// <param name="friendlyName">The display name of the column.</param>
    /// <param name="defaultLanguage"><c>true</c> if this column is for the default language.</param>
    /// <param name="isoCode">The code of the language to use for the Google translation button, "" (empty string) to show a 'disabled' button, null to disable it.</param>
    public GridViewTemplate(ListItemType type, string colname, string friendlyName, bool defaultLanguage, string isoCode) {
        templateType = type;
        columnName = colname;
        this.friendlyName = friendlyName;
        this.twoLetterISOCode = isoCode;
        this.defaultLanguage = defaultLanguage;
        
    }

    /// <summary>
    /// Adds the appropriate controls to a container
    /// </summary>
    /// <param name="container">The <see cref="T:System.Web.UI.Control"/> object to contain the instances of controls from the inline template.</param>
    public void InstantiateIn(Control container) {
        switch(templateType) {
            case ListItemType.Item:
            case ListItemType.AlternatingItem:
                    Label lblShowTranslation = new Label();
                        lblShowTranslation.EnableViewState = false;
                        lblShowTranslation.DataBinding += new EventHandler(lbl_DataBinding);
                    container.Controls.Add(lblShowTranslation);
                    break;
            case ListItemType.EditItem:
                Label lblTranslation = new Label();
                    lblTranslation.EnableViewState = false;
                    lblTranslation.Text = "Translation";
                    lblTranslation.CssClass = "block";
                    container.Controls.Add(lblTranslation);
                TextBox txtTranslation = new TextBox();
                    txtTranslation.ID = columnName;
                    lblTranslation.AssociatedControlID = txtTranslation.ID;
                    txtTranslation.TextMode = TextBoxMode.MultiLine;
                    txtTranslation.Rows = 4;
                    txtTranslation.EnableViewState = false;
                    txtTranslation.ValidationGroup = "editelement";
                    txtTranslation.DataBinding += new EventHandler(txt_DataBinding);
                    container.Controls.Add(txtTranslation);
                Literal br = new Literal();
                    br.Text = "<br />";
                    container.Controls.Add(br);
                HyperLink btnFindResource = new HyperLink();
                    btnFindResource.Text = I18nUtils.GetString("UIStrings", "FindSimilarTranslations");
                    btnFindResource.NavigateUrl = "#"+columnName; // pass the column name here for JQuery hookup in grd_PreRender
                    btnFindResource.CssClass = "findResource blockTrigger";
                    btnFindResource.ToolTip = I18nUtils.GetString("UIStrings", "LookupResourcesUsingTranslation", friendlyName);
                    btnFindResource.DataBinding += new EventHandler(btnFindResource_DataBinding);
                    container.Controls.Add(btnFindResource);
                if(twoLetterISOCode != null) {
                    if(twoLetterISOCode == "") {
                        HyperLink imgFillGoogle = new HyperLink();
                        imgFillGoogle.Text = I18nUtils.GetString("Errors", "LanguageNotSupported");
                        imgFillGoogle.CssClass = "gTranslateOff blockTrigger";
                        imgFillGoogle.ToolTip = I18nUtils.GetString("Errors", "LangNotSupportedGoogle", friendlyName);
                        imgFillGoogle.Enabled = false;
                        container.Controls.Add(imgFillGoogle);
                    } else {
                        HyperLink btnFillGoogle = new HyperLink();
                        btnFillGoogle.Text = I18nUtils.GetString("UIStrings", "TranslateUsingName", "Google");
                        btnFillGoogle.NavigateUrl = "#" + twoLetterISOCode; // pass the code here for JQuery hookup in grd_PreRender
                        btnFillGoogle.CssClass = "gTranslate blockTrigger";
                        btnFillGoogle.ToolTip = I18nUtils.GetString("UIStrings", "TranslateUsingNameDesc", friendlyName, "Google");
                        btnFillGoogle.DataBinding += new EventHandler(btnFillGoogle_DataBinding);
                        container.Controls.Add(btnFillGoogle);
                    }
                }
                container.Controls.Add(new LiteralControl("<img src=\"images/ajax-small.gif\" alt=\"" + I18nUtils.GetString("UIStrings", "Searching") + "\" class=\"ajax ajax-small\" />"));
                if(defaultLanguage) {
                    RequiredFieldValidator val = new RequiredFieldValidator();
                    val.ControlToValidate = txtTranslation.ID;
                    val.ErrorMessage = I18nUtils.GetString("Errors", "DefaultLanguageRequired");
                    val.SetFocusOnError = true;
                    val.Display = ValidatorDisplay.Dynamic;
                    val.ValidationGroup = "editelement";
                    container.Controls.Add(val);
                }
                Label lblComment = new Label();
                    lblComment.EnableViewState = false;
                    lblComment.Text = I18nUtils.GetString("UIStrings", "TranslatorsComment");
                    lblComment.CssClass = "block";
                    container.Controls.Add(lblComment);
                TextBox txtComment = new TextBox();
                    txtComment.ID = columnName + "-comment";
                    lblComment.AssociatedControlID = txtComment.ID;
                    txtComment.TextMode = TextBoxMode.MultiLine;
                    txtComment.Rows = 4;
                    txtComment.EnableViewState = false;
                    txtComment.ValidationGroup = "editelement";
                    container.Controls.Add(txtComment);
                break;
        }
    }

    /// <summary>
    /// Databinds the textbox and assigns it an ID based on the column name.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void txt_DataBinding(object sender, EventArgs e) {
        TextBox txtTranslation = sender as TextBox;
        GridViewRow row = txtTranslation.NamingContainer as GridViewRow;
        object dataValue = DataBinder.Eval(row.DataItem, columnName);
        if(dataValue != DBNull.Value) {
            txtTranslation.Text = dataValue.ToString();
        }
        if(defaultLanguage && txtTranslation.Text.Length == 0) {
            row.CssClass = "warning";
            row.Cells[0].ToolTip = I18nUtils.GetString("UIStrings", "DefaultLanguageMissing");
        }
    }

    /// <summary>
    /// Databinds the label.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void lbl_DataBinding(object sender, EventArgs e) {
        Label lbl = sender as Label;
        GridViewRow row = lbl.NamingContainer as GridViewRow;
        object dataValue = DataBinder.Eval(row.DataItem, columnName);
        if(dataValue != DBNull.Value) {
            string labelText = dataValue.ToString();
            lbl.Text = Utils.TrimText(labelText, 25);
            if(labelText.Length > 25) {
                lbl.ToolTip = labelText;
            }
        }
    }

    /// <summary>
    /// Sets the tooltip text and command argument for the 'find resource' button.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void btnFindResource_DataBinding(object sender, EventArgs e) {
        HyperLink btn = sender as HyperLink;
        GridViewRow row = btn.NamingContainer as GridViewRow;
        btn.ID = "dynfind-"+ row.DataItemIndex+'-'+ columnName;
    }

    protected void btnFillGoogle_DataBinding(object sender, EventArgs e) {
        HyperLink btn = sender as HyperLink;
        GridViewRow row = btn.NamingContainer as GridViewRow;
        btn.ID = "google-" + row.DataItemIndex + '-' + columnName;
    }
}